package es.cazadoresmadridejos.beans.facade;

import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import es.cazadoresmadridejos.beans.manager.temps.TempsManager;
import es.cazadoresmadridejos.model.Temps;

@Service
@RemoteProxy(name="commonFacade",creator=SpringCreator.class)
public class CommonFacade {

	@Autowired private TempsManager tempsManager;
	
	public String forwardToString(String url,HttpServletRequest request) throws ServletException, IOException{
		WebContext context = WebContextFactory.get();
		return context.forwardToString("/" + url);
	}

	public String forwardToStringDisplayTag(String url) throws ServletException, IOException{
		WebContext context = WebContextFactory.get();
		
		URL urlE = new URL(url);
		String path = urlE.getPath();
		String query = urlE.getQuery();
		
		String finalPath = path + "?" + query;
		if(finalPath.startsWith("/caza")){
			finalPath = finalPath.substring(5);
		}
		return context.forwardToString(finalPath);
	}

	public void changeOrder(Integer value){
		Temps temps = tempsManager.getByKey(Temps.BIG_GAME_ORDER);
		temps.setValue(value.toString());
		temps.setNumeric(value);
		
		tempsManager.save(temps);
	}
}
